import { Injectable } from '@nestjs/common';
import sequelize from 'src/util/sequelize';
import { AiChatMessages } from 'src/dao/AiChatMessages';
import {
  AiChatConversations,
  AiChatConversationsAttributes,
} from 'src/dao/AiChatConversations';
import { uuid } from 'uuidv4';
import { AiChatConversationsModel } from 'src/model/ai/chatConversations';
import { AiChatMessagesModel } from 'src/model/ai/chatMessages';
import { CommonResult } from '../util/commonResult';
import { AddMessageDto } from './dto/zitie.dto';
import { ThirdPartyService } from '../thirdParty/thirdParty.service';
import { Op } from 'sequelize';
import { commonPage } from '../util/commonPage';
import {
  WxAiChatMessages,
  WxAiChatMessagesAttributes,
} from 'src/dao/WxAiChatMessages';

// 微信用户接口 - 从 JWT token 解析获得
interface WxUserInfo {
  openid: string;
  loginTime: number;
  userId?: string;
  nickname?: string;
  avatarUrl?: string;
  loginCount?: number;
  unionid?: string;
}
@Injectable()
export class ZitieService {
  private AiChatConversationsModel: typeof AiChatConversations;
  private AiChatMessagesModel: typeof AiChatMessages;
  private WxAiChatMessagesModel: typeof WxAiChatMessages;
  private thirdPartyService: ThirdPartyService;

  constructor(thirdPartyService: ThirdPartyService) {
    this.thirdPartyService = thirdPartyService;
    this.WxAiChatMessagesModel = WxAiChatMessages.initModel(sequelize);
    this.AiChatConversationsModel =
      AiChatConversationsModel.initModel(sequelize);
    this.AiChatMessagesModel = AiChatMessagesModel.initModel(sequelize);
  }

  // 开始一个对话
  async startConversation(body: AiChatConversationsAttributes) {
    await this.AiChatConversationsModel.upsert({
      id: uuid(),
      ...body,
    });
    return CommonResult.success();
  }

  async getMessage(query: any, user: any) {
    const { pageNum = 1, pageSize = 10 } = query;
    const { userId } = user;
    // 先用降序拿出最新的条目
    const result = await commonPage<any>(
      this.AiChatMessagesModel,
      { pageNum, pageSize },
      {
        where: {
          userId,
        },
        order: [['createdTime', 'DESC']],
      },
    );
    // 然后再调转显示
    return CommonResult.success({
      ...result,
      records: result.records.reverse(),
    });
  }

  async getWxMessage(query: any, wxUser: WxUserInfo) {
    const { pageNum = 1, pageSize = 10 } = query;

    // 从 token 中解析出的微信用户信息，优先使用 userId，如果没有则使用 openid
    const userId = wxUser.userId || wxUser.openid;

    if (!userId) {
      return CommonResult.failed('用户信息无效');
    }

    // 先用降序拿出最新的条目
    const result = await commonPage<any>(
      this.WxAiChatMessagesModel,
      { pageNum, pageSize },
      {
        where: {
          userId,
        },
        order: [['createdTime', 'DESC']],
      },
    );

    // 然后再调转显示，并附加用户信息用于调试
    return CommonResult.success({
      ...result,
      records: result.records.reverse(),
      userInfo: {
        userId,
        openid: wxUser.openid,
        nickname: wxUser.nickname,
        loginCount: wxUser.loginCount,
      },
    });
  }

  async addWxMessage(body: AddMessageDto) {
    await this.WxAiChatMessagesModel.create({
      id: uuid(),
      ...body,
    });
    const { userId } = body;
    const historyData = await this.WxAiChatMessagesModel.findAll({
      where: {
        [Op.and]: { userId },
      },
      order: [['createdTime', 'ASC']],
    });
    const messages = historyData.map(({ content, role }) => {
      return {
        content,
        role,
      };
    });
    return CommonResult.success(messages);
  }

  async addMessage(body: AddMessageDto) {
    console.log(body);
    await this.AiChatMessagesModel.create({
      id: uuid(),
      ...body,
    });
    const { userId, deviceId } = body;
    const historyData = await this.AiChatMessagesModel.findAll({
      where: {
        [Op.and]: { userId, deviceId },
      },
      order: [['createdTime', 'ASC']],
    });
    const messages = historyData.map(({ content, role }) => {
      return {
        content,
        role,
      };
    });
    return CommonResult.success(messages);
  }

  async deleteMessage() {
    await this.AiChatMessagesModel.destroy({
      where: {
        deviceId: null,
      },
    });
  }
}
